package com.banzhi.shop.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonAdapter;
import com.banzhi.shop.entity.Discount.Discount_data;
import com.banzhi.shop.model.CallBack.DiscountCoponCallBack;
import com.banzhi.shop.model.IDiscountCoponModel;
import com.banzhi.shop.model.Impl.DiscountCoponImpl;
import com.banzhi.shop.utils.DateUtil;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ToastUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LeiHe on 2017/4/26.
 * 优惠券页面
 */

public class DiscountCoponFrg extends Fragment implements SwipeRefreshLayout.OnRefreshListener, DiscountCoponCallBack {
    /**
     * 选项卡的ID   用来展现不同的界面
     */
    private String id;
    private View view;
    private SwipeRefreshLayout srllistview;
    private RecyclerView recyclerview;
    private IDiscountCoponModel model;
    private int page = 1;
    private CommonAdapter<Discount_data> adapter;
    private List<Discount_data> data = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private boolean loading;
    private RelativeLayout rlnodata;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取传过来的fragment的id
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frg_discountcopon, container, false);
        initView();
        setListeners();
        model = new DiscountCoponImpl();
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        model.getData(id, page, this);
        return view;
    }

    private void initView() {
        srllistview = (SwipeRefreshLayout) view.findViewById(R.id.srl_listview);
        srllistview.setColorSchemeResources(R.color.themeColor);
        srllistview.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        srllistview.setOnRefreshListener(this);
        recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);
        rlnodata = (RelativeLayout) view.findViewById(R.id.rl_nodata);
    }

    private void setListeners() {
//        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                if (dy > 0) //向下滚动
//                {
//                    int visibleItemCount = layoutManager.getChildCount();
//                    int totalItemCount = layoutManager.getItemCount();
//                    int pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
//
//                    if (!loading && (visibleItemCount + pastVisiblesItems) >= totalItemCount) {
//                        loading = true;
//
//                    }
//                } else {
//                    loading = false;
//                }
//            }
//        });
        recyclerview.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                page++;
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                model.getData(id, page, DiscountCoponFrg.this);
            }
        });
    }


    public static DiscountCoponFrg newInstance(String id) {
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        DiscountCoponFrg testFm = new DiscountCoponFrg();
        testFm.setArguments(bundle);
        return testFm;

    }


    @Override
    public void onRefresh() {
        page = 1;
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        model.getData(id, page, this);
    }

    /**
     * @param object 获取数据成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        if (page == 1) {
            data.clear();
        } else {
            if (((List<Discount_data>) object).size() == 0) {
//                ToastUtils.makeToastShort("没有更多了");
                return;
            }
        }
        data.addAll((List<Discount_data>) object);
        if (data.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        if (adapter == null) {
            showViews();
            recyclerview.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private void showViews() {
        adapter = new CommonAdapter<Discount_data>(getContext(), R.layout.item_discount_copon, data) {
            @Override
            public void convert(ViewHolder holder, Discount_data discount_data, int position) {
                if (discount_data.getDeduct().isEmpty()) {
                    holder.setText(R.id.tv_money, NumberUtils.DecimalFormat(discount_data.getDeduct()));
                }
                holder.setText(R.id.tv_cotext, discount_data.getCouponname());
                holder.setText(R.id.tv_cotext1, discount_data.getCouponname());
                if ("1".equals(id)) {
                    holder.setText(R.id.tv_statu, "未使用");
                    holder.getTextView(R.id.tv_statu).setTextColor(ContextCompat.getColor(getContext(), R.color.Dis));
                } else if ("2".equals(id)) {
                    holder.setText(R.id.tv_statu, "已使用");
                } else if ("3".equals(id)) {
                    holder.setText(R.id.tv_statu, "已过期");
                }
                holder.setText(R.id.tv_qixian, DateUtil.getTimeData(discount_data.getTimeend()).substring(0, 10));
            }
        };
    }

    /**
     * @param object 获取数据失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
         NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
